package secret.test;

import javax.crypto.*;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

public class AES {
    static KeyGenerator kg;
    static SecretKey key;

    public static void main(String[] args) {
        init();//每次执行都会生成新的key
        deSecret();
    }

    static void init() {
        try {
            kg = KeyGenerator.getInstance("AES");//获取密钥生成器
            kg.init(128);//AES可以是128,192,256位、DES只为56位、DESede可以为112,168位

            key = kg.generateKey();
            System.out.println("key Encode:" + Arrays.toString(key.getEncoded()));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

    }

    static byte[] secret() {
        try {
            Cipher cp = Cipher.getInstance("AES");//创建密码器
            cp.init(Cipher.ENCRYPT_MODE, key);
            String str = "待加密文本。。。";
            byte[] ptext = str.getBytes();
            byte[] ctext = cp.doFinal(ptext);//加密
            System.out.println(Arrays.toString(ctext));
            System.out.println("加密后：" + new String(ctext));
            return ctext;
        } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException |
                 BadPaddingException e) {
            e.printStackTrace();
            return null;
        }
    }

    static void deSecret() {
        try {
            Cipher cp = Cipher.getInstance("AES");
            cp.init(Cipher.DECRYPT_MODE, key);
            byte[] ctext = secret();
            byte[] ptext = cp.doFinal(ctext);
            System.out.println(new String(ptext));
        } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException |
                 BadPaddingException e) {
            e.printStackTrace();
        }
    }

}
